<template>
    <div class="question-management">
        <el-card>
      <!-- 页面头部 -->
       <template #header>
      <div class="page-header">
        <div class="breadcrumb-section">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item @click="goBack" class="clickable">技术方向管理</el-breadcrumb-item>
                <el-breadcrumb-item @click="goNode" class="clickable">{{ stageInfo.categoryName }}</el-breadcrumb-item>
                <el-breadcrumb-item @click="goStage" class="clickable">{{ stageInfo.nodeName }}</el-breadcrumb-item>
                <el-breadcrumb-item>{{stageInfo.stageName}}</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
    </div>
    </template>
        <div class="header-info">
          <h2>{{ stageInfo.stageName }} - 题目管理</h2>
          <p class="info-text">关卡序号：{{ stageInfo.stageNumber }}  |  题目数：{{questionList.length}}</p>
        </div>
      
    
      <!-- 操作栏 -->
      <div class="operation-bar">
        <div class="left-operations">
          <el-button type="primary" @click="showCreateDialog = true">
            <el-icon><Plus /></el-icon>
            新建题目
          </el-button>
          <el-button @click="handleBatchImport">
            <el-icon><Upload /></el-icon>
            批量导入
          </el-button>
        </div>
        
        <div class="right-operations">
          <el-input
            v-model="searchText"
            placeholder="搜索题目标题或内容"
            style="width: 200px"
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          
          <el-select v-model="filterType" placeholder="题目类型" style="width: 120px" clearable @change="applyFilters">
            <el-option label="单选题" value="single_choice" />
            <el-option label="多选题" value="multiple_choice" />
            <el-option label="判断题" value="true_false" />
            <el-option label="填空题" value="fill_blank" />
            <el-option label="代码题" value="code" />
            <el-option label="问答题" value="essay" />
            <el-option label="拖拽题" value="drag_drop" />
            <el-option label="匹配题" value="match" />
            <el-option label="排序题" value="sort" />
            <el-option label="项目题" value="project" />
            <el-option label="交互题" value="interactive" />
          </el-select>
          
          <el-select v-model="filterDifficulty" placeholder="难度等级" style="width: 100px" clearable @change="applyFilters">
            <el-option label="1星" :value="1" />
            <el-option label="2星" :value="2" />
            <el-option label="3星" :value="3" />
            <el-option label="4星" :value="4" />
            <el-option label="5星" :value="5" />
          </el-select>
          
          <el-select v-model="filterStatus" placeholder="审核状态" style="width: 100px" clearable @change="applyFilters">
            <el-option label="待审核" value="pending" />
            <el-option label="已通过" value="approved" />
            <el-option label="已拒绝" value="rejected" />
            <el-option label="需复审" value="need_review" />
          </el-select>
        </div>
      </div>

      <!-- 题目列表 -->
      <div class="question-list">
        <el-table :data="questionList" style="width: 100%" v-loading="loading">
          <el-table-column type="selection" width="55" />
          
          <el-table-column prop="questionKey" label="题目编号" width="120" />
          
          <el-table-column label="题目标题" min-width="200">
            <template #default="scope">
              <div class="question-title">
                {{ scope.row.questionTitle }}
                <el-image 
                  v-if="scope.row.questionImage" 
                  :src="scope.row.questionImage"
                  style="width: 20px; height: 20px; margin-left: 8px"
                  fit="cover"
                  :preview-src-list="[scope.row.questionImage]"
                />
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="类型" width="100">
            <template #default="scope">
              <el-tag :type="getTypeTagType(scope.row.questionType)">
                {{ getTypeText(scope.row.questionType) }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column label="难度" width="80">
            <template #default="scope">
              <el-rate 
                v-model="scope.row.difficultyLevel" 
                disabled 
                show-score 
                text-color="#ff9900"
                score-template="{value}星"
              />
            </template>
          </el-table-column>
          
          <el-table-column prop="points" label="分值" width="80" />
          
          <el-table-column label="统计" width="120">
            <template #default="scope">
              <div class="stats">
                <div>使用: {{ scope.row.usageCount }}</div>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="审核状态" width="100">
            <template #default="scope">
              <el-tag :type="getStatusTagType(scope.row.auditStatus)">
                {{ getStatusText(scope.row.auditStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column label="质量评分" width="100">
            <template #default="scope">
              <el-rate 
                v-model="scope.row.qualityScore" 
                disabled 
                max="5"
                allow-half
              />
            </template>
          </el-table-column>
          
          <el-table-column label="创建时间" width="150">
            <template #default="scope">
              {{ formatDate(scope.row.createTime) }}
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button size="small" @click="handlePreview(scope.row)">预览</el-button>
              <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
              <el-dropdown @command="handleMoreAction">
                <el-button size="small">
                  更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item :command="{action: 'copy', row: scope.row}">复制</el-dropdown-item>
                    <el-dropdown-item :command="{action: 'audit', row: scope.row}">审核</el-dropdown-item>
                    <el-dropdown-item :command="{action: 'disable', row: scope.row}">
                      {{ scope.row.is_active ? '禁用' : '启用' }}
                    </el-dropdown-item>
                    <el-dropdown-item :command="{action: 'delete', row: scope.row}" divided>删除</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
  
        
      </div>
  
      <!-- 新建/编辑题目对话框 -->
      <el-dialog 
        v-model="showCreateDialog" 
        :title="editingQuestion ? '编辑题目' : '新建题目'"
        width="80%"
        :before-close="handleDialogClose"
      >
        <QuestionForm 
          ref="questionFormRef"
          :question="editingQuestion"
          :node-id="nodeId"
          @submit="handleSubmitQuestion"
          @cancel="handleCancelQuestion"
        />
      </el-dialog>
  
      <!-- 题目预览对话框 -->
      <el-dialog v-model="showPreviewDialog" title="题目预览" width="60%">
        <QuestionPreview 
          v-if="previewQuestion"
          :question="previewQuestion"
        />
      </el-dialog>
  
      <!-- 审核对话框 -->
      <el-dialog v-model="showAuditDialog" title="题目审核" width="50%">
        <el-form :model="auditForm" label-width="80px">
          <el-form-item label="审核状态">
            <el-radio-group v-model="auditForm.status">
              <el-radio value="approved">通过</el-radio>
              <el-radio value="rejected">拒绝</el-radio>
              <el-radio value="need_review">需复审</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="质量评分">
            <el-rate v-model="auditForm.qualityScore" max="5" allow-half />
          </el-form-item>
          <el-form-item label="审核备注">
            <el-input 
              v-model="auditForm.remark"
              type="textarea"
              :rows="4"
              placeholder="请输入审核备注"
            />
          </el-form-item>
        </el-form>
        
        <template #footer>
          <el-button @click="showAuditDialog = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitAudit">确定</el-button>
        </template>
      </el-dialog>
    </el-card>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, onMounted, computed, watch } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { Plus, Upload, MagicStick, Search, ArrowDown } from '@element-plus/icons-vue'
  import { get } from '@/axios'
  import QuestionForm from '@/components/QuestionForm.vue'
  import QuestionPreview from '@/components/QuestionPreview.vue'
  
  const route = useRoute()
  const router = useRouter()
  
  // 路由参数
  const stageInfo = reactive({
    stageId:route.query.stageId,
    stageKey:route.query.stageKey,
    stageName:route.query.stageName,
    stageNumber:route.query.stageNumber,
    nodeId:route.query.nodeId,
    nodeName:route.query.nodeName,
    categoryId:route.query.categoryId,
    categoryName:route.query.categoryName
  })

  
  // 响应式数据
  const loading = ref(false)
  const questionList = ref([])
  const total = ref(0)
  const currentPage = ref(1)
  const pageSize = ref(20)
  
  // 搜索和筛选
  const searchText = ref('')
  const filterType = ref('')
  const filterDifficulty = ref('')
  const filterStatus = ref('')
  
  // 对话框控制
  const showCreateDialog = ref(false)
  const showPreviewDialog = ref(false)
  const showAuditDialog = ref(false)
  const editingQuestion = ref(null)
  const previewQuestion = ref(null)
  const questionFormRef = ref(null)

  const filteredQuestionList = ref([]) // 筛选后的列表
const originalQuestionList = ref([]) // 原始数据列表

  const applyFilters = () => {
    let filtered = [...originalQuestionList.value]
    
    // 按题目类型筛选
    if (filterType.value) {
        filtered = filtered.filter(item => item.questionType === filterType.value)
    }
    
    // 按难度等级筛选
    if (filterDifficulty.value) {
        filtered = filtered.filter(item => item.difficultyLevel === filterDifficulty.value)
    }
    
    // 按审核状态筛选
    if (filterStatus.value) {
        filtered = filtered.filter(item => item.auditStatus === filterStatus.value)
    }
    
    // 按关键词搜索
    if (searchText.value) {
        const keyword = searchText.value.toLowerCase()
        filtered = filtered.filter(item => 
        item.questionTitle?.toLowerCase().includes(keyword) ||
        item.questionContent?.toLowerCase().includes(keyword)
        )
    }
    
    filteredQuestionList.value = filtered
    questionList.value = filtered // 更新显示的列表
}
  
  // 审核表单
  const auditForm = reactive({
    status: '',
    qualityScore: 0,
    remark: ''
  })
  
  //获取表单信息
  function fetchQuestionList(){
    loading.value = true
    get('/umsAdmin/getQuestion',{stageId:stageInfo.stageId},content=>{
        console.dir(content)
        questionList.value = content
        originalQuestionList.value = content // 保存原始数据
    })
    loading.value = false
  }
  
  // 题目类型映射
  const questionTypeMap = {
    single_choice: '单选题',
    multiple_choice: '多选题',
    true_false: '判断题',
    fill_blank: '填空题',
    code: '代码题',
    essay: '问答题',
    drag_drop: '拖拽题',
    match: '匹配题',
    sort: '排序题',
    project: '项目题',
    interactive: '交互题'
  }
  
  // 审核状态映射
  const auditStatusMap = {
    pending: '待审核',
    approved: '已通过',
    rejected: '已拒绝',
    need_review: '需复审'
  }
  
  // 工具函数
  const getTypeText = (type) => questionTypeMap[type] || type
  const getStatusText = (status) => auditStatusMap[status] || status
  
  const getTypeTagType = (type) => {
    const typeMap = {
      single_choice: '',
      multiple_choice: 'success',
      true_false: 'info',
      fill_blank: 'warning',
      code: 'danger',
      essay: 'primary'
    }
    return typeMap[type] || ''
  }
  
  const getStatusTagType = (status) => {
    const statusMap = {
      pending: 'warning',
      approved: 'success',
      rejected: 'danger',
      need_review: 'info'
    }
    return statusMap[status] || ''
  }
  
  const formatDate = (dateString) => {
    if (!dateString) return ''
    const date = new Date(dateString)
    return date.toLocaleString('zh-CN')
  }
  
  // 事件处理
  const handleSearch = () => {
    currentPage.value = 1
    fetchQuestionList()
  }
  
  
  const handleEdit = (question) => {
    editingQuestion.value = { ...question }
    showCreateDialog.value = true
  }
  
  const handlePreview = (question) => {
    previewQuestion.value = question
    showPreviewDialog.value = true
  }
  
  const handleMoreAction = ({ action, row }) => {
    switch (action) {
      case 'copy':
        handleCopy(row)
        break
      case 'audit':
        handleAudit(row)
        break
      case 'disable':
        handleToggleStatus(row)
        break
      case 'delete':
        handleDelete(row)
        break
    }
  }
  
  const handleCopy = async (question) => {
    try {
      const newQuestion = { ...question }
      delete newQuestion.id
      newQuestion.questionKey = `${question.questionKey}_copy_${Date.now()}`
      newQuestion.questionTitle = `${question.questionTitle} (副本)`
      
      await questionApi.create(newQuestion)
      ElMessage.success('题目复制成功')
      fetchQuestionList()
    } catch (error) {
      ElMessage.error('题目复制失败')
    }
  }
  
  const handleAudit = (question) => {
    editingQuestion.value = question
    auditForm.status = question.auditStatus
    auditForm.qualityScore = question.qualityScore
    auditForm.remark = question.audit_remark || ''
    showAuditDialog.value = true
  }
  
  const handleSubmitAudit = async () => {
    try {
      await questionApi.audit(editingQuestion.value.id, auditForm)
      ElMessage.success('审核完成')
      showAuditDialog.value = false
      fetchQuestionList()
    } catch (error) {
      ElMessage.error('审核失败')
    }
  }
  
  const handleToggleStatus = async (question) => {
    try {
      await questionApi.updateStatus(question.id, !question.is_active)
      ElMessage.success(`题目已${question.is_active ? '禁用' : '启用'}`)
      fetchQuestionList()
    } catch (error) {
      ElMessage.error('操作失败')
    }
  }
  
  const handleDelete = async (question) => {
    try {
      await ElMessageBox.confirm('确定要删除这道题目吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      
      await questionApi.delete(question.id)
      ElMessage.success('题目删除成功')
      fetchQuestionList()
    } catch (error) {
      if (error !== 'cancel') {
        ElMessage.error('题目删除失败')
      }
    }
  }
  
  const handleSubmitQuestion = async (questionData) => {
    try {
      if (editingQuestion.value) {
        await questionApi.update(editingQuestion.value.id, questionData)
        ElMessage.success('题目更新成功')
      } else {
        await questionApi.create({
          ...questionData,
          node_id: nodeId.value
        })
        ElMessage.success('题目创建成功')
      }
      
      showCreateDialog.value = false
      editingQuestion.value = null
      fetchQuestionList()
    } catch (error) {
      ElMessage.error(editingQuestion.value ? '题目更新失败' : '题目创建失败')
    }
  }
  
  const handleCancelQuestion = () => {
    showCreateDialog.value = false
    editingQuestion.value = null
  }
  
  const handleDialogClose = () => {
    if (questionFormRef.value?.hasUnsavedChanges()) {
      return ElMessageBox.confirm('有未保存的更改，确定要关闭吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return true
      }).catch(() => {
        return false
      })
    }
    return true
  }
  
  
  // 生命周期
  onMounted(() => {
    fetchQuestionList()
  })
  
  // 监听路由参数变化
  watch(() => route.query, () => {
    stageId.value = route.query.stageId
    stageKey.value = route.query.stageKey
    stageName.value = route.query.stageName
    stageNumber.value = route.query.stageNumber
    nodeId.value = route.query.nodeId
    nodeName.value = route.query.nodeName
    categoryId.value = route.query.categoryId
    categoryName.value = route.query.categoryName
    
    if (nodeId.value) {
      fetchQuestionList()
    }
  })
  
  const goBack = () => {
  router.push('/questions')
}
const goNode = () => {
  router.push({
    path:'/questions/knowledge',
    query: {
      categoryId: stageInfo.categoryId,
      categoryKey: route.query.categoryKey,
      categoryName: stageInfo.categoryName
    }
  })
}
const goStage = () => {
  router.push({
    path:'/questions/knowledge/stages',
    query: {
        nodeId:stageInfo.nodeId,
        nodeKey:route.query.nodeKey,
        nodeName:stageInfo.nodeName,
        categoryId: stageInfo.categoryId,
        categoryKey: route.query.categoryKey,
        categoryName: stageInfo.categoryName
    }
  })
}

  </script>
  
  <style scoped>
  .breadcrumb-section .clickable {
  cursor: pointer;
  color: #409eff;
  transition: all 0.3s ease;
}

.breadcrumb-section .clickable:hover {
  text-decoration: underline;
  transform: translateX(2px);
}
  .question-management {
    padding: 20px;
  }
  
  .page-header {
    margin-bottom: 20px;
  }
  
  .header-info {
    margin-top: 10px;
  }
  
  .header-info h2 {
    margin: 0 0 8px 0;
    color: #303133;
  }
  
  .info-text {
    margin: 0;
    color: #606266;
    font-size: 14px;
  }
  
  .operation-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 16px;
    background: #f8f9fa;
    border-radius: 8px;
  }
  
  .left-operations {
    display: flex;
    gap: 12px;
  }
  
  .right-operations {
    display: flex;
    gap: 12px;
    align-items: center;
  }
  
  .statistics {
    margin-bottom: 20px;
  }
  
  .stat-item {
    text-align: center;
  }
  
  .stat-number {
    font-size: 24px;
    font-weight: bold;
    color: #409eff;
    margin-bottom: 8px;
  }
  
  .stat-label {
    font-size: 14px;
    color: #606266;
  }
  
  .question-list {
    background: white;
    border-radius: 8px;
    padding: 20px;
  }
  
  .question-title {
    display: flex;
    align-items: center;
  }
  
  .stats div {
    font-size: 12px;
    color: #606266;
    line-height: 1.4;
  }
  
  .pagination {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }
  
  :deep(.el-table th) {
    background-color: #f8f9fa;
  }
  
  :deep(.el-card) {
    border: none;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }
  
  :deep(.el-breadcrumb) {
    font-size: 14px;
  }
  </style>